//
//  LBWOAuthViewController.swift
//  weibo
//
//  Created by Limonwei on 15/12/6.
//  Copyright © 2015年 heima. All rights reserved.
//document.getElementById('userId').value='LBW'document.getElementById('passwd').value='123456'/

//授权登陆界面

import UIKit
import SVProgressHUD

//登录需要一个常量  appkey app_secrect 宏定义
let WB_APPKEY = "3664526039"
let WB_APP_SECRET = "09117e91539f5c5d5688f5ed5369840e"
let WB_REDIRECT_URI = "http://www.itheima.com/"

class LBWOAuthViewController: UIViewController,UIWebViewDelegate {
    
    //懒加载一个网页
    private lazy var webView = UIWebView()
    
    //在导入视图里添加这个web
    override func loadView() {
        //添加网页视图
        webView.delegate = self
        
        //当前视图为webView
        view = webView
    }
    
    //视图加载完成后刷新
    override func viewDidLoad() {
        super.viewDidLoad()

     setupUI()
        
        //定义url  授权页面地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)"
        
        let url = NSURL(string: urlString)!
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
        
    }
    
    //设置UI
    private func setupUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "full")
        navigationItem.title = "微博登录"
        
        
    }
    
    //item监听方法
    @objc private func dismiss(){
        
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func full(){
        
        //自动填充用户名 密码
        printLog("自动填充")
        
        //用户名和密码
        let jsString = "document.getElementById('userId').value='13554644187';document.getElementById('passwd').value='199311055814'"
        //拼接
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    
    
//    
//    //webView开始网络请求
//    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        //
//        
//        guard let url = request.URL?.absoluteString else {
//            return true
//        }
//        
//        if !url.hasPrefix(WB_REDIRECT_URI) {
//            
//            return true
//        }
//        
//        
//        
//        //获取code
//        printLog(request.URL!.query)
//        
//        //截取授权code
//        let code = request.URL!.query!.substringFromIndex("code=".endIndex)
//        
//        //获取accessToken
//        loadAccessToken(code)
//        
//        return false
//        
//    }
    

    
//    //获取accessToken
//    private func loadAccessToken(code: String) {
//        //请求地址
//        let urlstring = "https://api.weibo.com/oauth2/access_token"
//        
//        //请求参数 (参数一定要对照着写对,拷贝)
//        let params = [
//            
//            "client_id":WB_APPKEY,
//            "client_secret":WB_APP_SECRET,
//            "grant_type":"authorization_code",
//            "code":code,
//            "redirect_uri":WB_REDIRECT_URI
//
//        ]
//        
//        //发送请求
//        LBWNetworkTools.shareTool.request(.POST, url: urlstring, params: params, callback: { (response, error) -> () in
//            
//            if error != nil {
//                printLog("请求错误:\(error)")
//                return
//            }
//            
//            // 在强转的时候,`!` 与 `?` 怎么选,只要看前面的数据是否是一个可选值
//            guard let dict = response as? [String: AnyObject] else {
//                printLog("返回数据不是字典")
//                return
//            }
//            
//            let account = LBWUserAccount(dict: dict)
//            
//            printLog(account)
//
//
//        })
//    }
    
}


//webView delegate
extension LBWOAuthViewController {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //拦截回调页,截取code,拿着code去获取accessToken
        guard let url = request.URL?.absoluteString else{
            return true
        }
        
        //如果判断到不是以回调页开头,就放行让其去加载
        if !url.hasPrefix(WB_REDIRECT_URI) {
            
            return true
        }
        
        if request.URL!.query!.hasPrefix("code=") {
            
            //获取code
            printLog(request.URL!.query)
            
            //截取授权code
            let code = request.URL!.query!.substringFromIndex("code=".endIndex)
            
            //获取accessToken
            LBWUserAccountViewModel.shareAccount.loadAccessToken(code, complete: { (isSuccess) -> () in
                if !isSuccess {
                    printLog("加载失败")
                    SVProgressHUD.showErrorWithStatus("网络异常,登录失败")
                    return
            }
                printLog("登陆成功")
                
                SVProgressHUD.dismiss()
                
                //关闭当前页面  登陆页面跳转欢迎页面
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //跳转到欢迎页面 ,切换控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(LBWSwitchRootVCNotifation, object: self)
                    
                })
        })
        }else{
            printLog(request.URL)
            
            //当前页面消失
            dismiss()
        }
        
        return false

}

    //显示转圈加载视图 第三方
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
        //SVProgressHUD.showInfoWithStatus("正在拼命加载中...", maskType: .Gradient)
        
        SVProgressHUD.setBackgroundColor(UIColor.clearColor())
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
}

}










